#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

static void* thread_func(void* arg)
{
  int j;
  printf("New thread started\n");
  for (j = 1; ; j++) {
    printf("Loop %d\n",j);
    sleep(1);
    pthread_testcancel();
  }
  return NULL;
}

int main(int argc, char *argv[])
{
  pthread_t thread;
  int s;
  void *res;

  s = pthread_create(&thread, NULL, thread_func, NULL);
  if (s != 0)
    printf("pthread_create failed\n");

  sleep(3);

  s = pthread_cancel(thread);
  if (s != 0)
    printf("pthread_cancel failed\n");

  s = pthread_join(thread,&res);
  if (s != 0)
    printf("pthread_join failed\n");

  if (res == PTHREAD_CANCELED)
    printf("Thread was canceled\n");
  else
    printf("Thread was not canceled\n");
  return 0;
}

